package com.fiidee.blog.service.impl;

import com.fiidee.blog.common.ERRORCODE;
import com.fiidee.blog.dto.UserDTO;
import com.fiidee.blog.entity.User;
import com.fiidee.blog.entity.UserCompany;
import com.fiidee.blog.mapper.UserCompanyMapper;
import com.fiidee.blog.mapper.UserMapper;
import com.fiidee.blog.service.UserService;
import com.fiidee.blog.util.CookieAndSessionUtil;
import com.fiidee.blog.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created by zzb on 2015/5/26.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCompanyMapper userCompanyMapper;
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<User> selectByDTO(UserDTO dto) {
        return userMapper.selectByDTO(dto);
    }

    @Override
    public int deleteInIds(String ids) {
        return userMapper.deleteInIds(ids);
    }

    private void setUserCookie(Map<String,Object> user,HttpServletResponse response){
        CookieAndSessionUtil.addCookie("userId", user.get("id") + "", response);
        CookieAndSessionUtil.addCookie("username", (String) user.get("username"), response);
        CookieAndSessionUtil.addCookie("name", (String) user.get("name"), response);
        CookieAndSessionUtil.addCookie("avatar", (String) user.get("avatar"), response);

    }

    private void removeUserCookie(HttpServletResponse response){
        CookieAndSessionUtil.removeCookie("userId", response);
        CookieAndSessionUtil.removeCookie("username", response);
        CookieAndSessionUtil.removeCookie("name", response);
        CookieAndSessionUtil.removeCookie("avatar",response);
    }

    private boolean isPasswordRight(User user,String password){
        String userPassword = user.getPassword();
        if(MD5Util.validateDoubleMD5(userPassword,password)){
            return true;
        }
        return false;
    }

    @Override
    public int doLogin(String loginCode, String password, HttpServletResponse response) {
        List<Map<String,Object>> users = userMapper.selectByMutiMethods(loginCode);
        if(null == users || 0 == users.size()){
            return ERRORCODE.NOUSER;
        }
        for(Map<String,Object> user : users){
            if(MD5Util.validateDoubleMD5((String)user.get("password"), password)){
                setUserCookie(user,response);
                return ERRORCODE.SUCCESS;
            }
        }
        return ERRORCODE.PASSWORDWRONG;
    }

    @Override
    public int doLogout(HttpServletResponse response) {
        removeUserCookie(response);
        return ERRORCODE.SUCCESS;
    }

    @Override
    public int doModifyPassword(Integer userId, String oldPassword, String newPassword) {
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ERRORCODE.NOUSER;
        }
        if(isPasswordRight(user, oldPassword)){
            User userUpdate = new User();
            userUpdate.setId(userId);
            userUpdate.setPassword(MD5Util.doubleMD5Generate(newPassword));
            userMapper.updateByPrimaryKeySelective(userUpdate);

        }else return ERRORCODE.PASSWORDWRONG;
        return ERRORCODE.SUCCESS;
    }

    @Override
    public int doModifyEmail(Integer userId, String password, String newEmail) {
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ERRORCODE.NOUSER;
        }
        if(isPasswordRight(user, password)){
            User userUpdate = new User();
            userUpdate.setId(userId);
            userUpdate.setEmail(newEmail);
            userMapper.updateByPrimaryKeySelective(userUpdate);

        }else return ERRORCODE.PASSWORDWRONG;
        return ERRORCODE.SUCCESS;
    }

    @Override
    public int doModifyMobile(Integer userId, String password, String newMobile) {
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ERRORCODE.NOUSER;
        }
        if(isPasswordRight(user, password)){
            User userUpdate = new User();
            userUpdate.setId(userId);
            userUpdate.setMobile(newMobile);
            userMapper.updateByPrimaryKeySelective(userUpdate);

        }else return ERRORCODE.PASSWORDWRONG;
        return ERRORCODE.SUCCESS;
    }

    @Override
    public int doModifyAvatar(Integer userId, String imgUrl, HttpServletResponse response) {
        UserCompany uc = userCompanyMapper.selectByUserId(userId);
        UserCompany update = new UserCompany();
        update.setAvatar(imgUrl);
        int count = 0;
        if(uc == null){
            update.setUserId(userId);
            count = userCompanyMapper.insertSelective(update);
        }else{
            update.setId(uc.getId());
            update.setUserId(userId);
            count = userCompanyMapper.updateByPrimaryKeySelective(update);
        }
        if(count != 0){
            CookieAndSessionUtil.addCookie("avatar", imgUrl, response);
            return ERRORCODE.SUCCESS;
        }else{
            return  ERRORCODE.UPDATEUSERERROR;
        }
    }

    @Override
    public int doModifyInfo(Integer userId,
                            String name,
                            String alias,
                            String realname,
                            String role,
                            String email,
                            String number,
                            String summary) {

        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ERRORCODE.NOUSER;
        }
        User userUpdate = new User();
        userUpdate.setId(userId);
        userUpdate.setName(name);
        userUpdate.setEmail(email);
        userUpdate.setSummary(summary);
        userMapper.updateByPrimaryKeySelective(userUpdate);

        UserCompany userCompany = userCompanyMapper.selectByUserId(userId);
        UserCompany userCompanyUpdate = new UserCompany();
        userCompanyUpdate.setAlias(alias);
        userCompanyUpdate.setNumber(number);
        userCompanyUpdate.setRealname(realname);
        userCompanyUpdate.setRole(role);
        if(userCompany == null){
            userCompanyUpdate.setUserId(userId);
            userCompanyMapper.insertSelective(userCompanyUpdate);
        }else{
            userCompanyUpdate.setId(userCompany.getId());
            userCompanyMapper.updateByPrimaryKeySelective(userCompanyUpdate);
        }
        return ERRORCODE.SUCCESS;
    }

    @Override
    public List<User> findUser(String name) {
        return userMapper.findUser(name);
    }

    @Override
    public List<Map<String, Object>> getRecommendUser() {
        return userMapper.selectRecommendUser();
    }

    @Override
    public Map<String, Object> getUserInfo(Integer userid) {
        return userMapper.getUserInfo(userid);
    }
}
